package cn.zyjblogs.starter.oauth.token;

import cn.zyjblogs.starter.common.entity.constant.ContextKeyConstant;
import cn.zyjblogs.starter.common.entity.context.BaseContext;
import cn.zyjblogs.starter.common.entity.dto.ContextDto;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zhuyijun
 */
@Component
public class OauthAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
        String userId = (String) map.get(ContextKeyConstant.USER_ID_KEY);
        String username = (String) map.get(ContextKeyConstant.USERNAME_KEY);
        String tenantId = (String) map.get(ContextKeyConstant.TENANT_ID_KEY);
        String name = (String) map.get(ContextKeyConstant.NAME_KEY);
        BaseContext.set(ContextDto.builder().userId(userId).username(username).token(value).name(name).tenantId(tenantId).build());
        return super.extractAccessToken(value, map);
    }

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        OAuth2Authentication oAuth2Authentication = super.extractAuthentication(map);
        oAuth2Authentication.setDetails(map);
        return oAuth2Authentication;
    }
}
